package com.zlsy.thread.flowcontrol.countdownlatch;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhouliang
 * @date 2020/9/2 15:17
 */
public class CountDownLatchDemo2 implements Runnable {

    private final CountDownLatch latch;
    private final CountDownLatch countDownLatch;

    public CountDownLatchDemo2(CountDownLatch latch, CountDownLatch countDownLatch) {
        this.latch = latch;
        this.countDownLatch = countDownLatch;
    }

    public static void main(String[] args) throws InterruptedException {
        int size = 5;
        final CountDownLatch latch = new CountDownLatch(1);
        final CountDownLatch countDownLatch = new CountDownLatch(size);
        CountDownLatchDemo2 r = new CountDownLatchDemo2(latch, countDownLatch);
        ExecutorService executorService = Executors.newFixedThreadPool(4);

        for (int i = 0; i < size; i++) {
            executorService.execute(r);
        }

        Thread.sleep(5000);

        //主线程发出信号，同一时刻请求某个接口
        latch.countDown();

        //等待所有接口调用接口结束
        countDownLatch.await();

        System.err.println("都跑完了！");

        executorService.shutdown();
    }

    @Override
    public void run() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //do post
        System.out.println(Thread.currentThread().getName() + "do post！");

        //模拟100个子线程调用http的响应耗时
        try {
            Thread.sleep(new Random().nextInt(1000));
            System.out.println(Thread.currentThread().getName() + "调用结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            countDownLatch.countDown();
        }
    }
}
